<template>
  <div class="dcy-content">
    <!-- 查询条件 -->
    <Form ref="queryParams" :model="queryParams" inline :label-width="60" label-position="left">
      <FormItem label="角色名">
        <Input v-model="queryParams.roleName" clearable placeholder="请输入角色名"/>
      </FormItem>
      <FormItem :label-width="0" class="search-btn-mar">
        <Button icon="md-search"  type="primary" @click="refresh()">查询</Button>
        <Button icon="md-refresh"  type="primary" @click="reset()">重置</Button>
        <Button icon="md-add" type="primary"  @click="addUser()">添加</Button>
        <Button icon="md-add" type="primary"  @click="removeBatch()" :disabled="delBtnDisabled">删除</Button>
      </FormItem>
    </Form>

    <!-- 表格 -->
    <dcy-table
      ref="dcyTable"
      unique-id="roleId"
      :query-params="queryParams"
      :url="url"
      @table-select-val="selectVal"
      :columns="columns">
      <template slot-scope="{ row, index }" slot="roleStatus">
        <Tag color="success" v-if="row.roleStatus === '0'">正常</Tag>
        <Tag color="error" v-if="row.roleStatus === '1'">禁用</Tag>
      </template>
      <template slot-scope="{ row, index }" slot="roleKey">
        {{row.roleKey.substring(5)}}
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <a @click="update(row)">修改</a>
        <Divider type="vertical"/>
        <a @click="remove(row)">删除</a>
        <Divider type="vertical"/>
        <a @click="authPower(row)">授权</a>
      </template>
    </dcy-table>

    <!-- 添加表单 -->
    <Modal
      v-model="dialogShow"
      :title="dialogTitle"
      :mask-closable="false"
      @on-cancel="handleReset('form')">
      <Form ref="form" :model="form" :rules="rules" :label-width="80">
        <FormItem label="名称" prop="roleName">
          <Input v-model="form.roleName" placeholder="请输入名称"/>
        </FormItem>
        <FormItem label="权限字符" prop="roleKey">
          <Input v-model="form.roleKey" placeholder="请输入权限字符"/>
        </FormItem>
        <FormItem label="状态" prop="roleStatus">
          <Select v-model="form.roleStatus" placeholder="请选择状态">
            <template v-for="item in statusOptionList">
              <Option :value="item.dictValue">{{item.dictLable}}</Option>
            </template>
          </Select>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
        </FormItem>
      </Form>
      <!-- 自定义按钮组 -->
      <div slot="footer">
        <Button type="text"  @click="handleReset('form')">取消</Button>
        <Button type="primary"  @click="handleSubmit('form')">确认</Button>
      </div>
    </Modal>

    <!-- 授权-->
    <Modal
      v-model="dialogAuthPowerShow"
      title="授权"
      width="600"
      :mask-closable="false"
      @on-ok="saveAuthPower"
      @on-cancel="cancelAuthPowerDialog">
      <Transfer
        v-if="dialogAuthPowerShow"
        filterable
        :data="powerList"
        :list-style="{width: '250px'}"
        :render-format="render"
        :titles="['权限列表','已授权列表']"
        :target-keys="targetKeys"
        :filter-method="filterMethod"
        @on-change="handleRoleChange"></Transfer>
    </Modal>
  </div>
</template>

<script>
    import DcyTable from '@/components/dcy/dcy-table'
    import {addRole, deleteBatchRoleById, deleteRoleById, updateRole} from '@/api/admin/role'
    import {noticeError, noticeSuccess} from '@/libs/notice'
    import {getPowerAllList} from "../../api/admin/power";
    import {getAuthPowerListByRoleId, saveAuthPower} from "../../api/admin/role";
    import {getDictByType} from "../../api/common";

    export default {
        name: 'role-manage',
        components: {DcyTable},
        data() {
            return {
                url: '/admin-service/role/page',
                columns: [
                    {title: '名称', key: 'roleName', align: 'center'},
                    {title: '权限字符', slot: 'roleKey', align: 'center'},
                    {title: '状态', slot: 'roleStatus', align: 'center'},
                    {title: '操作', slot: 'action', align: 'center'}
                ],
                queryParams: {},
                dialogShow: false,
                delBtnDisabled: true,
                ids: [],
                dialogTitle: '添加角色',
                form: {},
                rules: {
                    roleName: [this.$ruler('角色名称')],
                    roleKey: [this.$ruler('角色权限字符串'), {pattern: /^[A-Z_]{3,10}$/, message: '请输入大写字母或者下划线并且3-10个字符'}],
                    roleStatus: [this.$ruler('角色状态')]
                },
                roleId: null,
                dialogAuthPowerShow: false,
                powerList: [],
                targetKeys: [],
                statusOptionList:[],
            }
        },
        methods: {
            /**
             * 刷新
             */
            refresh() {
                // 清空选中状态
                this.$refs.dcyTable.selectAll(false);
                this.$refs.dcyTable.refresh()
            },
            /**
             * 重置搜索条件
             */
            reset() {
                this.queryParams = {}
            },
            /**
             * 修改弹出框
             * @param row
             */
            update(row) {
                this.form = {...row};
                this.form.roleKey = this.form.roleKey.substring(5);
                this.dialogTitle = '修改角色';
                this.dialogShow = true
            },
            /**
             * 添加弹出框
             */
            addUser() {
                this.dialogTitle = '添加角色';
                this.dialogShow = true
            },
            /**
             * 批量删除
             */
            removeBatch() {
                this.$Modal.confirm({
                    title: '您确认删除所选内容吗？',
                    onOk: () => {
                        deleteBatchRoleById(this.ids).then(res => {
                            if (res.data) {
                                noticeSuccess('del')
                            } else {
                                noticeError('del')
                            }
                            this.refresh()
                        })
                    }
                })
            },
            /**
             * 提交表单
             * @param name
             */
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.form.roleKey = 'ROLE_' + this.form.roleKey;
                        if (this.dialogTitle === '添加角色') {
                            addRole(this.form).then(res => {
                                if (res.data) {
                                    noticeSuccess('add')
                                } else {
                                    noticeError('add')
                                }
                                this.cancelDialogAndRefresh()
                            })
                        } else {
                            updateRole(this.form).then(res => {
                                if (res.data) {
                                    noticeSuccess('upd')
                                } else {
                                    noticeError('upd')
                                }
                                this.cancelDialogAndRefresh()
                            })
                        }
                    }
                })
            },
            /**
             * 行内删除
             * @param row
             */
            remove(row) {
                this.$Modal.confirm({
                    title: '您确认删除这条内容吗？',
                    onOk: () => {
                        deleteRoleById(row.roleId).then(res => {
                            if (res.data) {
                                noticeSuccess('del')
                            } else {
                                noticeError('del')
                            }
                            this.refresh()
                        })
                    }
                })
            },
            /**
             * 重置表单
             * @param name
             */
            handleReset(name) {
                this.form = {};
                this.dialogShow = false;
                this.$refs[name].resetFields()
            },
            /**
             * 关闭弹出框 和 刷新表格
             */
            cancelDialogAndRefresh() {
                // 清空表单
                this.handleReset('form');
                // 刷新表格
                this.refresh()
            },
            /**
             * 点击每一行的checkbox
             */
            selectVal(ids) {
                this.ids = ids;
                this.delBtnDisabled = !this.ids.length
            },
            filterMethod(data, query) {
                return data.label.indexOf(query) > -1;
            },
            render(item) {
                return item.label + ':' + item.powTypeName;
            },
            cancelAuthPowerDialog() {
                this.dialogAuthPowerShow = false;
            },
            handleRoleChange(newTargetKeys) {
                this.targetKeys = newTargetKeys;
            },
            authPower(row) {
                this.roleId = row.roleId;
                getPowerAllList().then(res => {
                    if (res.success) {
                        let powerList = [];
                        res.data.forEach(e => {
                            let powTypeName = null;
                            switch (e.powType) {
                                case '0':
                                    powTypeName = '模块权限';
                                    break;
                                case '1':
                                    powTypeName = '菜单权限';
                                    break;
                            }
                            let power = {
                                key: e.powId,
                                label: e.powName,
                                powTypeName: powTypeName,
                                disabled: e.powStatus === '1'
                            };
                            powerList.push(power);
                        });
                        this.powerList = powerList;
                    }
                });
                getAuthPowerListByRoleId(this.roleId).then(res => {
                    this.targetKeys = res.data.map(e => e.powId);
                });
                this.dialogAuthPowerShow = true;
            },
            saveAuthPower() {
                let rolePowerDTO = {
                    roleId: this.roleId,
                    powerIds: this.targetKeys
                };
                saveAuthPower(rolePowerDTO).then(res => {
                    if (res.data) {
                        noticeSuccess('d')
                    } else {
                        noticeError('d')
                    }
                    // 刷新表格
                    this.refresh()
                })
            }
        },
        mounted() {
            getDictByType('status').then(res=>{
                this.statusOptionList = res.data;
            })
        }
    }
</script>

<style scoped>

</style>
